package switchviz.core.view;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseEvent;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.event.TreeSelectionEvent;

import org.apache.log4j.Logger;

import switchviz.core.ResourceManager;
import switchviz.graphic.GraphicFactory;
import switchviz.graphic.gauge.GaugeNodeModel;
import switchviz.graphic.gauge.IGauge;
import switchviz.gui.component.IListener;
import switchviz.gui.component.PopupMenu;
import switchviz.gui.component.XMLTreeNode;
import switchviz.util.FileOperations;

public class ViewPanel extends JPanel implements IListener, ComponentListener
{

	/**
	 * 
	 */
	private static Logger logger = Logger.getLogger(ViewPanel.class);
	private static final long serialVersionUID = -2697636465064235955L;
	private ViewConfigurationPanel _configpanel = null;
	private ViewTreePanel _treepanel = null;
	private ViewGaugeConfigurationPanel _gaugepanel = null;
	private PopupMenu _popup = null;
	private ViewDataModel _datamodel = null;
	private JButton _buttapply = null;
	private IGauge _actgauge = null;
	private ViewNewGaugeDialog _gaugedialog = null;
	
	public ViewPanel()
	{
		if (logger.isInfoEnabled()) { logger.info("Initialize ..."); }
		this.initialize();
	}
	
	private void initialize()
	{
		_buttapply = new JButton("Apply Changes");
		_buttapply.setActionCommand(ResourceManager.getInstance().getActionApply());
		_buttapply.addActionListener(this);
        
		JPanel buttonpanel = new JPanel();
        buttonpanel.setLayout(new BoxLayout(buttonpanel, BoxLayout.LINE_AXIS));
        buttonpanel.add(Box.createHorizontalGlue());
        buttonpanel.add(_buttapply);
        
		JPanel setuppanel = new JPanel(new BorderLayout());
		setuppanel.add(getConfigurationPanel(), BorderLayout.NORTH);
		setuppanel.add(getGaugePanel(), BorderLayout.CENTER);
		setuppanel.add(buttonpanel, BorderLayout.SOUTH);
		
		this.setLayout(ResourceManager.getInstance().getBorderLayout());
		this.add(getTreePanel(), BorderLayout.WEST);
		this.add(setuppanel, BorderLayout.CENTER);
		
		this.addComponentListener(this);
	}
	
	private ViewTreePanel getTreePanel()
	{
		if(_treepanel == null)
			try
			{
				_treepanel = new ViewTreePanel();
				_treepanel.addListener(this);
				_treepanel.getComboBox().setSelectedIndex(0);
				_popup = new PopupMenu(new String[]{ResourceManager.getInstance().getActionAddGauge(), ResourceManager.getInstance().getActionCopyGauge(), 
							ResourceManager.getInstance().getActionRemoveGauge(), ResourceManager.getInstance().getActionRefresh()}, this);
			}
			catch(Exception e) 
			{
				if (logger.isDebugEnabled()) { logger.debug(e.getMessage()); }
			}
		return _treepanel;
	}
	
	private ViewConfigurationPanel getConfigurationPanel()
	{
		if (_configpanel == null)
		{
			_configpanel = new ViewConfigurationPanel();
		}
		return _configpanel;
	}
	
	private ViewGaugeConfigurationPanel getGaugePanel()
	{
		if (_gaugepanel == null)
			_gaugepanel = new ViewGaugeConfigurationPanel();
		return _gaugepanel;
	}
	
	public void actionPerformed(ActionEvent ev) 
	{
		String command = ev.getActionCommand();
		try
		{
		    if (ResourceManager.getInstance().getActionSelect().equals(command))
		    {
		    	if(getTreePanel().getComboBox().getItemCount() == 0)
		    		return;
		    	
		    	_datamodel = (ViewDataModel)getTreePanel().getComboBox().getSelectedItem();

		    	if(_datamodel != null)
		    	{
		    		getTreePanel().loadNewView(_datamodel.getFile());
		    		getConfigurationPanel().setDataModel(_datamodel);
		    		if(getTreePanel().getViewTree().getTree().isSelectionEmpty())
		    			getGaugePanel().clearGaugeSpace();
		    	}
		    }
		    else if (ResourceManager.getInstance().getActionNew().equals(command))
		    {
		    	getTreePanel().createNewView();
		    	getGaugePanel().clearGaugeSpace();
		    	_actgauge = null;
		    }
		    else if (ResourceManager.getInstance().getActionApply().equals(command))
		    {
		    	int index = getTreePanel().getComboBox().getSelectedIndex();
		    	getTreePanel().getViewTree().updateView(getConfigurationPanel().getDataModel());
		    	if(_actgauge != null)
		    		getTreePanel().getViewTree().updateActElement(_actgauge.getElement());
		    	//getTreePanel().getViewTree().saveXML();
		    	getTreePanel().getViewTree().reNameAndSave(getConfigurationPanel().getDataModel().getName());
		    	getTreePanel().reload();
		    	getTreePanel().getComboBox().setSelectedIndex(index);
		    }
		    else if (ResourceManager.getInstance().getActionCopy().equals(command))
		    {
		    	int index = getTreePanel().getComboBox().getSelectedIndex();
		    	getTreePanel().copyView();
		    	getTreePanel().reload();
		    	getTreePanel().getComboBox().setSelectedIndex(index);
		    }
		    else if (ResourceManager.getInstance().getActionDelete().equals(command))
		    {
		    	ViewDataModel datamodel = (ViewDataModel)getTreePanel().getComboBox().getSelectedItem();
		    	if(getTreePanel().getComboBox().getItemCount() == 1)
		    		getTreePanel().createNewView();
		    
		    	FileOperations.deleteFile(datamodel.getFile());
		    	getTreePanel().getComboBox().removeItem(datamodel);
		    	getTreePanel().loadNewView(ViewTree.getFirstConfiguration());
		    }
		    else if (ResourceManager.getInstance().getActionAddItem().equals(command))
		    {
		    	GaugeNodeModel gnm = _gaugedialog.getGaugeNodeModel();
		    	_gaugedialog.setVisible(false);
		    	if (gnm.getName().length() == 0)
		    	{
		    		JOptionPane.showMessageDialog(this,
	    				    "Please insert a name for the new gauge.",
	    				    "Form not complete!",
	    				    JOptionPane.WARNING_MESSAGE);
	    			return;
		    	}	
		    	
		    	IGauge gauge = GraphicFactory.getInstance().getGauge(gnm.getType(), getTreePanel().getViewTree().newGaugeListElement(gnm.getType(), gnm.getName()));

		    	int index = getTreePanel().getComboBox().getSelectedIndex();
		    	getGaugePanel().setGaugeSpace(gauge.getSetupPanel());
		    	//getTreePanel().getViewTree().updateView(getConfigurationPanel().getDataModel(), _actgauge.getElement());
		    	getTreePanel().getViewTree().saveXML();
		    	getTreePanel().reload();
		    	getTreePanel().getComboBox().setSelectedIndex(index);
		    }
		    else if (ResourceManager.getInstance().getActionRemoveGauge().equals(command))
		    {
		    	getTreePanel().getViewTree().removeNode();
		    	getTreePanel().getViewTree().saveXML();
		    }
		    else if (ResourceManager.getInstance().getActionRefresh().equals(command))
		    {
		    	getTreePanel().reload();
		    }
		    else if (ResourceManager.getInstance().getActionAddGauge().equals(command))
		    {
		    	_gaugedialog = ViewNewGaugeDialog.getInstance();
		    	_gaugedialog.setGaugeNodeModel(null);
		    	_gaugedialog.addActionListener(this);
		    }
		    else if (ResourceManager.getInstance().getActionCopyGauge().equals(command))
		    {
		    	getTreePanel().getViewTree().copyNode();
		    	int index = getTreePanel().getComboBox().getSelectedIndex();
		    	getTreePanel().getViewTree().saveXML();
		    	getTreePanel().reload();
		    	getTreePanel().getComboBox().setSelectedIndex(index);
		    }
		}
		catch (Exception e1) 
		{ 
			e1.printStackTrace();
			
			logger.error(e1.getMessage()); 
		}
	}

	public void valueChanged(TreeSelectionEvent evt) 
	{
		XMLTreeNode currentnode = (XMLTreeNode)evt.getPath().getLastPathComponent();
		if (currentnode.getElement().getName().equals(ViewTree.GAUGENODE))
		{
			String gaugetype = currentnode.getElement().getAttributeValue(ViewTree.GAUGEATTTYPE); 
			_actgauge = GraphicFactory.getInstance().getGauge(gaugetype, currentnode.getElement());
			getGaugePanel().setGaugeSpace(_actgauge.getSetupPanel());
		}
		else
		{
			getGaugePanel().clearGaugeSpace();
		}
	}

	public void mousePressed(MouseEvent e) 
	{
		if (e.isPopupTrigger() || e.getButton() == 3) 
            _popup.show(e.getComponent(), e.getX(), e.getY());
	}
	
	public void componentShown(ComponentEvent evt) 
	{
		try 
		{
			getTreePanel().reload();
		} 
		catch (Exception e) 
		{
			logger.error(e.getMessage()); 
			e.printStackTrace();
		}
	}
	
	public void componentHidden(ComponentEvent arg0) {}
	public void componentMoved(ComponentEvent arg0) {}
	public void componentResized(ComponentEvent arg0) {}
	
	public void mouseClicked(MouseEvent arg0) {}
	public void mouseEntered(MouseEvent arg0) {}
	public void mouseExited(MouseEvent arg0) {}
	public void mouseReleased(MouseEvent arg0) {}
}
